/*
 * @Author: 凌宇king
 * @Date: 2022-09-18 10:34:57
 * @LastEditTime: 2022-09-27 08:08:20
 */
//加载express框架 
const express = require('express');
//实例路由
const router = express.Router();
//导入数据模型
const admin = require('../model/admin');
//===============API写下面================================================
router.get('/wxGetPower/:id', async (req, res) => {
    try {
        const role = await admin.find({ openid: req.params.id })
        // console.log(role[0].role)
        res.send({ role: role[0].role })
    }
    catch (error) {
        res.send({ status: 'error' })
    }
})
//管理后台 登录判断 
router.post('/admCkLogin', async (req, res) => {
    try {
        const result = await admin.findOne(req.body)
        if (result) {
            res.send({ status: 'success', info: result })
        }
        else {
            res.send({ status: 'fail' })
        }
    }
    catch (error) {
        res.send({ status: 'err' })
    }
})
//管理后台 获取所有管理员
router.get('/admGetAdmins', async (req, res) => {
    try {
        const { currentPage: page, pagesize } = req.query
        //获取数据库中的记录总数
        const total = await admin.countDocuments()
        //分页获取管理员
        const result = await admin.find().skip((page - 1) * pagesize).limit(pagesize).sort({ time: -1 })
        // console.log(result)
        res.send({
            status: 'success',
            total,
            result
        })
    } catch (error) {
        console.log(error)
        res.send({
            status: 'fail'
        })
    }
})
router.get('/adminList', async (req, res) => {
    const id = JSON.parse(req.query.id)._id
    const data = await admin.find({ _id: id })
    res.send({ role: data[0] })
})
//保存管理员
router.post('/saveAdmin',
    async (req, res) => {
        const { _id } = req.body
        if (_id) {
            admin.updateOne({ _id }, req.body).then(result => {
                // console.log(res)
                res.send('update')
            }).catch(err => {
                console.log(err)
                res.send('fail')
            })
        } else {
            admin.create(req.body).then(result => {
                res.send('save')
            }).catch(err => {
                console.log(err)
                res.send('fail')
            })
        }
    })
//删除管理员 
router.get('/delAdmin', async (req, res) => {
    const { _id } = req.query
    admin.findByIdAndRemove(_id).then(result => {
        res.send('success')
    }).catch(err => { res.send('fail') })
})
//===============API写在上面============================================= 
//导出路由
module.exports = router;